import React, { Component } from 'react';
// import PropTypes from "prop-types";
import { connect } from 'dva';
import { Table, Popconfirm, Button, message } from 'antd';
import moment from 'moment';
import Authorized, { checkAuthority } from 'utils/Authorized';
import AdminEditForm from 'components/permissionset/mgtpower/roleeditre';
import RoleEditForm from 'components/permissionset/mgtpower/roleeditresource';

@connect(state => ({
  global: state.global,
  mgtpower: state.mgtpower,
}))
export default class Pages extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false, //是否展示新增Modal
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      modalType: '',
      formDatas: null,
      roleVisible: false, //是否展示新增Modal
      recordAllRoleResource: {},
      currentId: '', //保存点击事件id
    };
  }
  componentDidMount() {
    this.getList({ pageNum: 1, pageSize: 10 });
  }

  /**
   * 数据获取
   */
  getList = payload => {
    this.props.dispatch({
      type: 'mgtpower/getList',
      payload,
    });
  };

  //翻页按钮
  handlePageChange = (pageNum, pageSize) => {
    this.getList({ pageNum, pageSize });
  };

  // 处理列表单选框事件
  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys });
  };

  //批量删除
  handleBathDelete = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'mgtpower/delete',
      payload: { selectedRowKeys },
      callback: res => {
        if (res.code === 200) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
        }
      },
    });
  };

  //关闭新增角色
  HandleCloseadminModal = () => {
    this.setState({
      visible: false,
    });
  };

  //打开新增角色
  HandleOpenadminModal = (type, datas) => {
    this.setState({
      visible: true,
      modalType: type,
      formDatas: datas || null,
    });
  };

  //新增 编辑角色回调
  addManage = values => {
    const { dispatch } = this.props;
    const { modalType, currentId } = this.state;
    if (modalType === 'edit') {
      dispatch({
        type: 'mgtpower/edit',
        payload: {
          id: currentId,
          values,
        },
      });
      this.HandleCloseadminModal('edit');
    } else {
      dispatch({
        type: 'mgtpower/add',
        payload: { values },
      });

      this.HandleCloseadminModal('add');
    }
  };

  // 编辑角色
  handleModalVisible = record => {
    // 打开编辑框
    this.setState({
      modalType: 'edit',
      currentId: record.id,
    });
    this.HandleOpenadminModal('edit', record);
  };

  //关闭分配资源Modal
  HandleCloseRoleResourceModal = () => {
    this.setState({
      roleVisible: false,
    });
  };

  //打开分配资源Modal
  HandleOpenRoleResourceModal = record => {
    // 获取编辑数据
    const { dispatch } = this.props;
    this.setState({
      roleVisible: true,
      currentId: record.id,
    });
    dispatch({
      type: 'mgtpower/getResourceList',
      payload: { roleId: record.id },
      callback: response => {
        if (response.code === 200) {
          this.setState({
            currentId: record.id,
            roleVisible: true,
            recordAllRoleResource: response.data,
            formDatas: record || null,
          });
        }
      },
    });
  };

  //分配资源回调
  addRoleResource = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'mgtpower/editResource',
      payload: {
        values,
        roleId: this.state.currentId,
      },
    });
    this.HandleCloseRoleResourceModal();
  };

  render() {
    const {
      mgtpower: { page, loading, visibleDTM },
      global: { departOptions, diseOptions },
    } = this.props;
    const {
      visible,
      selectedRowKeys,
      modalType,
      formDatas,
      roleVisible,
      recordAllRoleResource,
    } = this.state;
    const { checkedKeys, treeData } = recordAllRoleResource;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
    };
    const pagiNation = {
      pageSize: page.pageSize,
      total: page.total,
      current: page.pageNum,
      onChange: this.handlePageChange,
    };

    //表格列定义
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id',
      },
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '角色描述',
        dataIndex: 'remark',
        key: 'remark',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        key: 'createDate',
        render: createDate => {
          return null == createDate ? null : moment(createDate).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        render: record => (
          <div>
            <span>
              <Authorized authority={() => checkAuthority('role:update')} noMatch={<div />}>
                <a onClick={() => this.handleModalVisible(record)}>编辑</a>
              </Authorized>
            </span>
            &emsp;&emsp;
            <span>
              <Authorized authority={() => checkAuthority('refRoleAuth:add')} noMatch={<div />}>
                <a onClick={() => this.HandleOpenRoleResourceModal(record)}>分配资源</a>
              </Authorized>
            </span>
          </div>
        ),
      },
    ];

    return (
      <>
        <AdminEditForm
          visible={visible}
          modalType={modalType}
          onCancel={this.HandleCloseadminModal}
          onOk={values => this.addManage(values)}
          record={formDatas}
        />
        <RoleEditForm
          visible={roleVisible}
          modalType="multiple"
          onCancel={this.HandleCloseRoleResourceModal}
          onOk={values => this.addRoleResource(values)}
          allDatas={treeData}
          record={checkedKeys}
        />
        <div>
          <h3 className="head">角色管理</h3>
          <div style={{ padding: ' 10px 20px' }}>
            <Authorized authority={() => checkAuthority('role:add')} noMatch={<div />}>
              <Button
                type="primary"
                icon="plus"
                onClick={this.HandleOpenadminModal}
                className="mr10"
              >
                新增
              </Button>
            </Authorized>
            <span>
              <Authorized authority={() => checkAuthority('role:batchDelete')} noMatch={<div />}>
                {selectedRowKeys.length > 0 && (
                  <Popconfirm
                    title="删除的数据不能恢复，确定要全部删除吗?"
                    onConfirm={this.handleBathDelete}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button
                      className="ml10"
                      type="primary"
                      disabled={
                        null != selectedRowKeys && selectedRowKeys.length > 0 ? false : true
                      }
                      icon="delete"
                    >
                      {null != selectedRowKeys && selectedRowKeys.length > 1 ? '批量删除' : '删除'}
                    </Button>
                  </Popconfirm>
                )}
              </Authorized>
            </span>

            <Table
              style={{ marginTop: '10px' }}
              rowSelection={rowSelection}
              columns={columns}
              rowKey={record => record.id}
              loading={loading}
              dataSource={page.list}
              pagination={pagiNation}
            />
          </div>
        </div>
      </>
    );
  }
}
